﻿//------------------------------------------------------------
// GenericPool
// Copyright © 2025 Mao Yin Hang. All rights reserved.
//------------------------------------------------------------
namespace BaseStateMachine
{
    public abstract class BaseStateMachine<TState> 
        where TState : BaseState
    {
        private TState? _state;
        private Queue<TState?> _statesQueue;
        public TState? CurrentState => _state;
        public BaseStateMachine()
        {
            _statesQueue = new Queue<TState?>();
        }

        public void ChangeState<TState1>() where TState1 :TState
        {
            TState? state = GetState<TState1>();
            _statesQueue.Enqueue(state);
            if (_statesQueue.Count > 1)
            {
                return;
            }

            while (_statesQueue.Count > 0)
            {
                var changeState = _statesQueue.Peek();
                _state?.OnLeave();
                ReleaseState(_state);
                _state = changeState;
                _state?.OnEnter();
                _statesQueue.Dequeue();
            }
        }
        public abstract T? GetState<T>()
            where T : TState;

        public abstract void ReleaseState<T>(T? state)
            where T : TState;
    }
}
